package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/diogoxiang/smock/database"
	"github.com/diogoxiang/smock/controllers"
	"github.com/diogoxiang/smock/services"
)

func main() {
	// 初始化数据库
	database.InitDB()

	// 创建Gin实例
	r := gin.Default()

	// 允许跨域
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// API路由组
	api := r.Group("/api")
	{
		// Mock API管理
		api.GET("/mock", controllers.GetAllMockAPIs)
		api.GET("/mock/:id", controllers.GetMockAPI)
		api.POST("/mock", controllers.CreateMockAPI)
		api.PUT("/mock/:id", controllers.UpdateMockAPI)
		api.DELETE("/mock/:id", controllers.DeleteMockAPI)

		// 历史记录API
		api.GET("/logs", controllers.GetAllRequestLogs)
		api.GET("/logs/:id", controllers.GetRequestLog)
		api.DELETE("/logs/:id", controllers.DeleteRequestLog)
		api.DELETE("/logs", controllers.ClearRequestLogs)
	}

	// Mock服务路由 - 所有未匹配的路由都会被当作mock请求处理
	r.NoRoute(services.HandleMockRequest)

	// 获取端口配置
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	// 启动服务器
	log.Println("Server started on http://localhost:" + port)
	if err := r.Run(":" + port); err != nil {
		log.Fatal("Failed to start server:", err)
	}
}